const Koa = require("koa");
const app = new Koa();
const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const router = require("koa-router")();
// const logger = require('koa-logger') //关闭koa2自带日志
const log4js = require("./utils/log4j");
const jwt = require("jsonwebtoken");
const koajwt = require("koa-jwt");

const users = require("./routes/users");
const menus = require("./routes/menus");
const roles = require("./routes/roles");
const depts = require("./routes/depts");
const leaves = require("./routes/leaves");
// error handler
onerror(app);

require("./config/db");
const util = require("./utils/util");

//设置跨域访问
app.use(async (ctx, next) => {
    ctx.set("Access-Control-Allow-Origin", "*");
    ctx.set("Access-Control-Allow-Headers", "Content-Type,Content-Length,Authorization,Accept,X-Requested-With");
    ctx.set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    if (ctx.method == "OPTIONS") {
        ctx.body = 200;
    } else {
        await next();
    }
});

// middlewares
app.use(
    bodyparser({
        enableTypes: ["json", "form", "text"],
    })
);
app.use(json());
// app.use(logger()) //关闭koa2自带日志

// 自定义logger
app.use(async (ctx, next) => {
    log4js.info("get params " + JSON.stringify(ctx.request.query));
    log4js.info("post params " + JSON.stringify(ctx.request.body));
    await next().catch((error) => {
        if (error.status === 401) {
            //koajwt抛出401，但是这里处理仍然让前端请求成功200，在返回值里报token过期的相关内容
            ctx.status = 200;
            ctx.body = util.fail("Token认证失败", util.CODE_AUTH_ERROR);
        } else {
            throw error;
        }
    });
});

//拦截token校验
app.use(
    koajwt({ secret: "admin" }).unless({
        //不拦截某个接口
        path: ["/api/users/login"],
    })
);

router.prefix("/api");
router.use(users.routes());
router.use(menus.routes());
router.use(roles.routes());
router.use(depts.routes());
router.use(leaves.routes());
// routes
app.use(router.routes(), router.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
    log4js.error(err.stack);
});

module.exports = app;
